package com.sanchunhui.psc.ui.fragment

import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder
import cn.bingoogolapple.refreshlayout.BGARefreshLayout
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.kennyc.view.MultiStateView
import com.sanchuihun.psc.ui.fragment.BaseMvpFragment
import com.sanchunhui.psc.R
import com.sanchunhui.psc.common.BaseApplication
import com.sanchunhui.psc.data.protocol.Member
import com.sanchunhui.psc.data.protocol.Project
import com.sanchunhui.psc.data.protocol.ResponseInfo
import com.sanchunhui.psc.data.protocol.Team
import com.sanchunhui.psc.ext.startLoading
import com.sanchunhui.psc.injection.component.DaggerTeamMemberComponent
import com.sanchunhui.psc.injection.module.TeamMemberModule
import com.sanchunhui.psc.presenter.MyTeamMemberPresenter
import com.sanchunhui.psc.presenter.ProjectTeamsPresenter
import com.sanchunhui.psc.presenter.view.MyTeamMemberView
import com.sanchunhui.psc.ui.activity.LoginActivity
import com.sanchunhui.psc.ui.activity.MemberDeviceMessageActivity
import com.sanchunhui.psc.ui.adapter.BaseRecyclerViewAdapter
import com.sanchunhui.psc.ui.adapter.TeamMembersAdapter
import kotlinx.android.synthetic.main.fragment_project_teams.*
import kotlinx.android.synthetic.main.fragment_project_teams.mMultiStateView
import kotlinx.android.synthetic.main.fragment_project_teams.mRefreshLayout
import kotlinx.android.synthetic.main.fragment_team_members.*
import kotlinx.android.synthetic.main.header.*
import org.jetbrains.anko.startActivity
import org.json.JSONObject

/**
 * @Author zyx
 * @Date 2021/4/12-11:05
 * @Dscribe 登陆角色为小组负责人时，显示人员列表主界面
 */

class TeamMembersFragment: BaseMvpFragment<MyTeamMemberPresenter>(), MyTeamMemberView, BGARefreshLayout.BGARefreshLayoutDelegate , View.OnClickListener {

    private lateinit var teamMembersAdapter : TeamMembersAdapter

    private var mMemberList : MutableList<Member> = mutableListOf()

    private lateinit var teamInfo : Team

    private var mCurrentPage: Int = 1
    private var mMaxPage: Int = 1

    private var mLeaderMemberId : Int = 0

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        return inflater?.inflate(R.layout.fragment_team_members,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initHeader()
        initView()
        initRefreshLayout()
    }

    override fun onStart() {
        super.onStart()
        initTeamInfo()
    }

    fun initHeader() {
        ll_team_headerTitle.visibility = View.VISIBLE
        // 分组开工
        tv_start.setOnClickListener {
            changeTeamStatus("start")
        }

        //分组收工
        tv_pause.setOnClickListener {
            changeTeamStatus("pause")
        }
    }

    /*
       小组状态操作
    */
    fun changeTeamStatus(status:String) {

        if (status.equals("start") && teamInfo.status.equals("start")) {
            val toast = Toast.makeText(context, "该组已经开工", Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
        } else if (status.equals("pause") && teamInfo.status.equals("pause")) {
            val toast = Toast.makeText(context, "该组已经收工", Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
        } else {
            val user = BaseApplication.mUser
            var message : String = ""
            var title : String = ""

            if (status.equals("start")) {
                message = "是否允许该组开工"
                title = String.format(context!!.getString(R.string.open_team))
            } else if (status.equals("pause")) {
                message = "是否允许该组收工"
                title = String.format(context!!.getString(R.string.pause_team))
            }
            AlertDialog.Builder(context)
                .setTitle(title)
                .setMessage(message)
                .setNegativeButton(R.string.cancel, null)
                .setPositiveButton(R.string.confirm, DialogInterface.OnClickListener {
                        dialogInterface, i ->  mPresenter.changeTeamStatus(teamInfo.id, user.token.toString(), status)

                })
                .show()
        }
    }

    private fun initView() {
        mMemberListRv.layoutManager = LinearLayoutManager(context)
        teamMembersAdapter = TeamMembersAdapter(context!!)
        mMemberListRv.adapter = teamMembersAdapter
        teamMembersAdapter.setOnItemClickListener(object : BaseRecyclerViewAdapter.OnItemClickListener<Member> {
            override fun onItemClick(item: Member, position: Int) {
                val intent = Intent(context, MemberDeviceMessageActivity::class.java)
                context!!.startActivity(intent)
            }
        })
        mMultiStateView.viewState = MultiStateView.ViewState.CONTENT
    }

    /*
        请求小组信息
     */
    private fun initTeamInfo() {
        val user = BaseApplication.mUser
        mPresenter.getMyTeamInfo(user.token.toString())
    }

    /*
      加载数据
    */
    private fun loadData() {
        val user = BaseApplication.mUser
        mMultiStateView.startLoading()
        mPresenter.getMyTeamMember(user.token.toString())
    }

    /*
     初始化刷新视图
  */
    private fun initRefreshLayout() {
        mRefreshLayout.setDelegate(this)
        val viewHolder = BGANormalRefreshViewHolder(context, true)
        viewHolder.setLoadMoreBackgroundColorRes(R.color.common_bg)
        viewHolder.setRefreshViewBackgroundColorRes(R.color.common_bg)
        mRefreshLayout.setRefreshViewHolder(viewHolder)
    }

    override fun injectComponent() {
        DaggerTeamMemberComponent.builder().activityComponent(mActivityComponent).teamMemberModule(TeamMemberModule()).build().inject(this)
        mPresenter.mView = this
    }

    // 获取小组信息
    override fun onGetMyTeamInfoResult(result: ResponseInfo) {
        if (result.code == 0) {
            teamInfo = Gson().fromJson(result.data.toString(), Team::class.java)
            mLeaderMemberId = teamInfo.leader_member_id
            if (teamInfo.name.isNotEmpty()) {
                tv_team_title.text = teamInfo.name
                tv_count.text = "(0/${teamInfo.member_cnt})"
            }
            if (teamInfo.status.equals("start")) {
                tv_team_status_start.visibility = View.VISIBLE
                tv_team_status_pause.visibility = View.GONE
                tv_team_status_complete.visibility = View.GONE
            } else if (teamInfo.status.equals("pause")) {
                tv_team_status_start.visibility = View.GONE
                tv_team_status_pause.visibility = View.VISIBLE
                tv_team_status_complete.visibility = View.GONE
            } else if (teamInfo.status.equals("complete")) {
                tv_team_status_start.visibility = View.GONE
                tv_team_status_pause.visibility = View.GONE
                tv_team_status_complete.visibility = View.VISIBLE
            }
            loadData()
        } else if (result.code == 401) {
            val toast = Toast.makeText(context, "登录失效，请重新登录", Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
            context!!.startActivity<LoginActivity>()
        }
    }

    override fun onChangTeamStatusResult(result: ResponseInfo) {
        if (result.code == 0) {
            val toast = Toast.makeText(context, "操作成功", Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
            initTeamInfo()
        } else {
            val toast = Toast.makeText(context, "操作失败", Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
        }

    }

    /*
        请求小组成员结果
    */
    override fun onGetMyTeamMemberResult(result: ResponseInfo) {
        mRefreshLayout.endLoadingMore()
        mRefreshLayout.endRefreshing()
        if (result.code == 0) {
            val json = result.data
            parserJson(json.toString())
        } else if (result.code == 401) {
            val toast = Toast.makeText(context, "登录失效，请重新登录", Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
            context!!.startActivity<LoginActivity>()
        }
    }

    override fun onError(text: String) {
        super.onError(text)
        if (mMemberList.size < 0) {
            mMultiStateView.viewState = MultiStateView.ViewState.EMPTY
        }
    }

    /*
        解析数据
    */
    fun parserJson(json: String) {
        val gson = Gson()
        var jsonObject = JSONObject(json)
        var members = jsonObject.getString("members")
        var memberList : ArrayList<Member> = gson.fromJson(members, object : TypeToken<List<Member>>() {}.type)

        if (memberList.isNotEmpty()) {
            mMemberList = memberList
            teamMembersAdapter.setData(memberList)
            teamMembersAdapter.leadeMemberId = mLeaderMemberId
            mMultiStateView.viewState = MultiStateView.ViewState.CONTENT
        } else {
            mMultiStateView.viewState = MultiStateView.ViewState.EMPTY
        }
    }

    override fun onBGARefreshLayoutBeginLoadingMore(refreshLayout: BGARefreshLayout?): Boolean {
        return if (mCurrentPage < mMaxPage) {
            mCurrentPage++
            loadData()
            true
        } else {
            false
        }
    }

    override fun onBGARefreshLayoutBeginRefreshing(refreshLayout: BGARefreshLayout?) {
        mCurrentPage = 1
        initTeamInfo()
    }

    override fun onClick(p0: View?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}
